package backend.product.manager;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.hibernate.Hibernate;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.product.model.Product;
import core.util.HibernateCoreUtil;

public class ProductAttributeManager  extends HibernateCoreUtil
{
	static int count=0;
	public String getSingleValueAttributeByName(Product p,String attributeName)
	{
		String val = new String("");
		if(attributeName == null || p == null)
		{
			return null ;
		}
		if(attributeName != null)
		{
			attributeName = attributeName.trim() ;
		}
		String sql = "select pav.value value from productav pav , product p , attribute a where p.uuid = pav.product_uuid and p.uuid =" +p.getUuid()+ " and pav.attribute_uuid = a.uuid and a.name = '"+attributeName+"'" ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		transaction = session.beginTransaction();
		SQLQuery query = session.createSQLQuery(sql).addScalar("value", Hibernate.STRING);
		List<String> valueLst = query.list();
		if(valueLst.size() > 0)
		{
			val = valueLst.get(0);
		}
		transaction.commit();
		session.close();
		return val ;
	}
	
																																	
	
	public int getReviewCount(Product p)
	{
		int val = 0 ;
		if( p == null)
		{
			return 0 ;
		}
		String sql="select count(*) review from ratingandreview rating where rating.product_uuid=" +p.getUuid();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		transaction = session.beginTransaction();
		SQLQuery query = session.createSQLQuery(sql).addScalar("review", Hibernate.INTEGER);
		List<Integer> valueLst = query.list();
		if(valueLst.size() > 0)
		{
			val = valueLst.get(0);
		}
		transaction.commit();
		session.close();
		return val ;
	}
	
	public int getRating(Product p)
	{
		int val = 0 ;
		if( p == null)
		{
			return 0 ;
		}
		String sql="select rating rating1 from ratingandreview rating where rating.product_uuid=" +p.getUuid();
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		transaction = session.beginTransaction();
		SQLQuery query = session.createSQLQuery(sql).addScalar("rating1", Hibernate.INTEGER);
		List<Integer> valueLst=query.list();
		if(valueLst.size() > 0)
		{
			for(int i=0;i<valueLst.size();i++)  
			{  
				val=val+valueLst.get(i); 
				count++;
			} 
			val=val/count;
		}
		
		transaction.commit();
		session.close();
		return val ;
	}


	
}
